import {createRouter, createWebHashHistory} from 'vue-router'
import {getToken} from "@/util/tokenUtil.js";
import axios from "@/util/axios.js";
import pinia from "@/stores/index.js";
import {useMenuStore} from "@/stores/menu.js";

const store = useMenuStore(pinia)

// const modules = import.meta.glob("../views/**")
// const resolveComponent = (path) => {
//     return modules[`../views/${path}`]
// }

const staticRoutes = [
    {
        path: '/login',
        meta: {
            title: '登录'
        },
        component: () => import('@/views/Login.vue')
    },
    {
        path: '/',
        name: 'Layout',
        meta: {
            title: '主页'
        },
        component: () => import('@/layout/index.vue'),
        children: [
            {
                path: 'index',
                meta: {
                    title: '首页'
                },
                component: () => import('@/views/welcome.vue'),
            }
        ]
    },
    {path: '/404', name: 'NotFound', meta: {title: '404找不到页面'}, component: () => import('../views/404.vue')},
    {path: '/:pathMatch(.*)', redirect: '/404'}
]

const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL),
    routes: staticRoutes,
})

router.beforeEach(async (to, from, next) => {
    if (to.meta.title) {
        document.title = '后台管理系统-' + to.meta.title
    }
    if (to.path === '/login') {
        return next()
    }
    const token = getToken()
    if (!token) return next('/login')
    // 判断是否有菜单加载了
    if (!store.menuList || store.menuList.length <= 0) {
        // 查询权限菜单
        const menusResponse = await axios.get('/aclpermission/userPermission')
        store.setMenuList(menusResponse.data.info)
    }
    return next()
})


export default router
